<?php
/**
 * File containing the BRail_LdapZendAuthTiein_Adapter class.
 * @package BRail_LdapZendAuthTiein
 */

/**
 * @package BRail_LdapZendAuthTiein
 */
class BRail_LdapZendAuthTiein_Adapter implements Zend_Auth_Adapter_Interface
{
    /**
     * @var array
     */
    private $_config;

    /**
     * @var BRail_LdapZendAuthTiein_Identity_Adapter_Interface
     */
    private $_identityAdapter;

    /**
     * @param array $config
     * @param BRail_LdapZendAuthTiein_Identity_Adapter_Interface $identity
     * @throws BRail_Ldap_Exception
     */
    public function __construct(array $config, BRail_LdapZendAuthTiein_Identity_Adapter_Interface $identity = null)
    {
        if (!((isset($config['username'])) && (isset($config['password']))
                    && (isset($config['host'])) && (isset($config['port'])))) {
            if (!(isset($config['host']) && isset($config['port']))) {
                $standardConfig = require_once 'config/environment.php';
                $this->_config = array(
                    'host' => $standardConfig[getenv('ENVPHP')]['host'],
                    'port' => $standardConfig[getenv('ENVPHP')]['port'],
                    'username' => $config['username'],
                    'password' => $config['password']
                );
            } else {
                throw new BRail_Ldap_Exception(
                    'Config array passed to '.__METHOD__.' misses some parameters.'
                );
            }
        } else {
            $this->_config = $config;
        }
        $this->_identityAdapter = $identity;
    }

    /**
     * @return Zend_Auth_Result
     */
    public function authenticate()
    {
        try {
            new BRail_Ldap_Adapter($this->_config);
        } catch (BRail_Ldap_Exception $e) {
            return new Zend_Auth_Result(
                Zend_Auth_Result::FAILURE,
                'unknown',
                array($e->getMessage())
            );
        }

        if (!isset($this->_identityAdapter)) {
            $identity = $this->_config['username'];
        } else {
            $identity = $this->_identityAdapter->getIdentity($this->_config['username']);
            if (!$identity) {
                return new Zend_Auth_Result(
                    Zend_Auth_Result::FAILURE,
                    'unknown',
                    array('No identity returned by identity adapter')
                );
            }
        }
        return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $identity);
    }
}